from datetime import datetime, timedelta
import os
import random
import uuid

import simplejson

from google.appengine.api import channel
from google.appengine.api import memcache 
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from gaesessions import get_current_session


from models import Scan, Store, Product



class ScanHandler(webapp.RequestHandler):
    def get(self):
        stuff={}
        #push_to_channels(random_scan())
        # Get the current session        
        session = get_current_session()
        
        # Get the value of the counter,
        # defaulting to 0 if not present
        session_id = session.get('counter', 0)
        if session_id==0:
            session['counter']=random.randint(0,1000000)
       
        blah={
        'blah':session_id

        }
        path = os.path.join(os.path.dirname(__file__), 'templates', 'scan.html')
        self.response.out.write(template.render(path, blah))
    
    def post(self):
        #self.response.out.write("Hi AMnada")
        blah=list()
        session=get_current_session()
        latitude=self.request.POST["latitude"]

        longitude=self.request.POST["longitude"]
        altitude=self.request.POST["altitude"]
        blah.append(altitude)
        speed=self.request.POST["speed"]
        heading=self.request.POST["heading"]
       
        self.response.out.write("Hi Amanda!!!")
        push_to_channels(latitude, longitude, altitude, speed, heading, session.get('counter'))
       

class MapHandler(webapp.RequestHandler):
    def get(self):
        channel_id = uuid.uuid4().hex
        token = channel.create_channel(channel_id)

        channels = simplejson.loads(memcache.get('channels') or '{}')
    
        channels[channel_id] = str(datetime.now())

        memcache.set('channels', simplejson.dumps(channels))

        template_values = {
            'token': token
        }

        path = os.path.join(os.path.dirname(__file__), 'templates', 'map.html')
        self.response.out.write(template.render(path, template_values))

class ChannelCleanupHandler(webapp.RequestHandler):
    def get(self):
        delete_inactive_channels()

        self.response.out.write("Deleted old channels")

def random_scan():
    return Scan(store=random.choice(STORES),
                product=random.choice(PRODUCTS),
                timestamp=datetime.now())

def push_to_channels(latitude, longitude, altitude, speed, heading, session_id):
    stuff=list()
    content = '''
    <div class="infowindowcontent">
      <table>
      <tr>
      <td class="prod_img">
        <strong>%(latitude)s</strong>
      </td>
      <td class="prod_info">
        <strong>%(longitude)s</strong><br/><em>%(altitude)s</em><br><em>%(speed)s
      </td>
      </tr>
      </table>
    </div>''' % { 'latitude': latitude,
                  'longitude' : longitude,
                  'altitude': altitude,
                  'speed': speed }
                  
            
    

    channels = simplejson.loads(memcache.get('channels') or '{}')
    
    message = {'lat': latitude,
               'lon': longitude,
               'content': "Latitude: " + latitude+"<br/>"+"Longitude: "+ longitude+"<br/>"+"Altitude: "+altitude+"<br/>"+"Speed: "+ speed+"<br/>"+"Heading: "+heading,
               'altitude': altitude,
               'speed': speed,
               'heading': heading,
               'session_id': session_id
               }
    for channel_id in channels.iterkeys():
        encoded_message = simplejson.dumps(message)

        channel.send_message(channel_id, encoded_message)

def delete_inactive_channels():
    channels = simplejson.loads(memcache.get('channels') or '{}')

    now = datetime.now()
    for channel_id, created in channels.items():
        
        dt = datetime.strptime(created.split(".")[0], "%Y-%m-%d %H:%M:%S")

        # NOTE: normally this would be 60 minutes; set it lower to expose the refresh behavior
        if (now - dt) > timedelta(minutes=1):
            del channels[channel_id]
            
            message = {'refresh': 'y'}
            channel.send_message(channel_id, simplejson.dumps(message))
                
        memcache.set('channels', simplejson.dumps(channels))

def main():
    application = webapp.WSGIApplication([('/', MapHandler),
                                          ('/scan', ScanHandler),
                                          ('/cleanup', ChannelCleanupHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
